import cameraView from '@/components/cameraView.vue';
import { createApp } from 'vue';
import { sceneCode } from '@/utils';

export async function init() {
    // 层级切换
    await loadMap();
    const campus = await createCampus(); // 创建园区
    // window.app.camera.flyTo(window.app.query('.Campus')[0]);
    /* window.app.camera.flyTo({
        object: campus,
        isEarth: true, // 是否在地球上，默认 false。在地球上使用需要传 true
        time: 3000,
    }); */

    // change后会移动相机到campus
    window.app.level.change(campus, {
        complete: async () => {
            await initPoint(); // 初始化点位
            await loadPoint(); // 加载点位
            createCustomMarker(); // 创建自定义maker
            createdLine(); // 创建线
            createFence(); // 创建围栏
        },
    });
}

function addClick() {
    const list = window.twinsManagerIns.twinsArray.filter((item) =>
        ['CE_SHI_SHE_XIANG_TOU'].includes(item.twinClassCode)
    );
    list.forEach((item) => {
        const model = window.app.query(`##${item.uuid}`)[0];
        model.on('click', (e) => {
            console.log(111);
        });
    });
}

/* 加载地球 */
const loadMap = () => {
    return new Promise((resolve, reject) => {
        window.app.create({
            type: 'Map',
            url: 'https://city.thingjs.com/ra/file/fetch/df/file/0AD4BC0DB2868ACD7CCA47F0BA0CC11B37C20DEFA71F26D79AA43D91A05F6F8A51F70274C3E492E636B1923AB5B9A2A49C4F8E802C534C620DBDFDD513D529D68D07C6C209711261/map.json',
            complete: (event) => {
                console.log(event);
                // const terrainLayer = window.app.query('.TerrainLayer')[0];
                // terrainLayer.url = ''; // 移除地形
                resolve();
            },
        });
    });
};

// 创建园区
const createCampus = () => {
    return new Promise((resolve, reject) => {
        window.campusManagerIns = window.TiIns.CampusManager({
            app: window.app, // THINGJS实例
            core: window.TiIns.Core, // 核心实例
            sceneCode,
            flyToSetting: true, // 园区，建筑，楼层默认飞到设置视角 - 默认true
            initChildScene: true, // 加载主场景时是否加载子场景 默认false
            lon: 109.19603656797783,
            lat: 34.6477393474472,
            height: -10, // 离地高度
            angle: 0,
            childSceneBeginLoad: () => {
                console.log('子场景开始加载');
            },
            childSceneLoaded: () => {
                console.log('子场景加载完毕');
            },
            sceneLoaded: (campus) => {
                console.log('主场景加载完毕');
                resolve(campus);
            },
        });
    });
};

/* 创建围栏 */
function createFence() {
    const lineData = window.twinsManagerIns.twinsArray.filter(
        (i) => i.twinClassCode === 'CE_SHI_MIAN'
    );
    lineData.forEach((line) => {
        const points = JSON.parse(line.cb_data).vertices;
        // 转换为地图的坐标
        const mapPoints = points.map((it) =>
            window.campusManagerIns.curCampus.selfToWorld([it[0], it[1], it[2]])
        );
        const trasData = window.TiIns.Utils.transformPoints({
            points: mapPoints,
            closed: true,
            radius: 5,
        });
        window.twinsManagerIns.createBoundary({
            uuid: line.uuid,
            name: '围栏',
            points: mapPoints,
            userData: line,
            height: 10,
            color: '#FF00FF',
            // emissive: '#FF0000',
            // opacity: 0.1,
            direction: 'y',
            // scroll: true,
            // speed: -1,
            // image: '/test/testImg/boundary.png',
            customMarker: {
                // el: createEle(),
                // url: testMarker,
                // keepSize: false,
                size: 0,
                // localPosition: [0, 10, 0],
                // pivot: [1, 1],
                // alwaysOnTop: false
            },
            modelCb: (obj) => {
                console.log('围栏创建', obj);
            },
            markerCb: (obj) => {
                console.log('围栏marker创建', obj);
                // 添加点击事件等
            },
        });
    });
}

/* 相机环绕 */
function cameraSurround() {
    const list = [
        {
            position: [
                1725345.6876438905, 3626163.448601111, 4955100.670557181,
            ],
            target: [1725335.9767495007, 3626162.581380118, 4955102.895070144],
            time: 2000,
        },
        {
            position: [
                1725051.2300188905, 3626163.601247575, 4955206.058392656,
            ],
            target: [1725041.684003626, 3626160.699508994, 4955206.733304597],
            time: 8000,
        },
        {
            position: [
                1725034.9710586076, 3626170.205337036, 4955205.102846755,
            ],

            target: [1725036.722976989, 3626160.8985325117, 4955208.314726506],
            time: 2000,
        },
        {
            position: [
                1725074.6399346152, 3625994.9681933806, 4955319.815821784,
            ],
            target: [1725076.1371445553, 3625985.5713113537, 4955322.891365872],
            time: 8000,
        },
    ];
    let idx = 0;
    const deepFly = (item) => {
        if (!item) return;
        window.app.camera.flyTo({
            isEarth: true, // 是否在地球上，默认 false。在地球上使用需要传 true
            time: item.time, // 飞行过程的时间，单位：毫秒
            position: item.position,
            target: item.target,
            complete() {
                // 飞行结束时的回调函数
                deepFly(list[++idx]);
            },
        });
    };
    deepFly(list[idx]);
}

window.cameraSurround = cameraSurround;

/* 创建路线 */
function createdLine() {
    // const list = window.twinsManagerIns.getCurrentModelByCode(['XIAN_CE_SHI']); // 获取线
    const lineData = window.twinsManagerIns.twinsArray.filter(
        (i) => i.twinClassCode === 'XIAN_CE_SHI'
    );
    lineData.forEach((line) => {
        const points = JSON.parse(line.cb_data).vertices;
        // 转换为地图的坐标
        const mapPoints = points.map((it) =>
            window.campusManagerIns.curCampus.selfToWorld([it[0], it[1], it[2]])
        );
        window.twinsManagerIns.createRouteLine({
            uuid: line.uuid,
            name: 'routeLine',
            points: mapPoints,
            userData: line,
            color: '#FF00FF',
            // emissive: '#FF0000',
            // opacity: 0.1,
            scroll: true, // 图片滚动
            // image: '/test/testImg/routeLine.png',
            arrowCap: false,
            customMarker: {
                // el: createEle(),
                // url: testMarker,
                // keepSize: false,
                size: 0,
                // localPosition: [0, 10, 0],
                // pivot: [1, 1],
                // alwaysOnTop: false
            },
            modelCb: (obj) => {
                console.log('routeLine创建', obj);
            },
            markerCb: (obj) => {
                console.log('routeLine marker创建', obj);
                // 添加点击事件等
            },
        });
    });
}

/* 自定义maker */
function createCustomMarker() {
    const camera = window.twinsManagerIns.twinsArray.filter(
        (i) => i.twinClassCode === 'CE_SHI_SHE_XIANG_TOU'
    );
    camera.forEach((item) => {
        const parent = window.app.query(`##${item.uuid}`)[0];
        parent.scale = [3, 3, 3]; // 设置缩放
        parent.on('click', (e) => {
            const childMark = window.app.query(`#marker_${item.UniqueCode}`);
            console.log(childMark);
            childMark.forEach((it) => {
                it.visible = !it.visible;
            });
        });
        window.app.create({
            type: 'Marker',
            name: `marker_${item.UniqueCode}`,
            id: `marker_${item.UniqueCode}`,
            // url: '/test/testImg/testMarker.png',
            visible: false, // 是否显示
            element: document.createElement('div'),
            keepSize: true,
            parent,
            pivot: [0.5, 1], // 偏移
            inheritScale: false, // 物体缩放是否受父物体影响, 默认 true
            scale: [1, 1, 1],
            size: 1,
            alwaysOnTop: true,
            inhertVisible: true, // 根据父元素显隐
            complete: (ev) => {
                const marker = ev.object;
                createApp({
                    setup() {
                        return {};
                    },
                    render() {
                        return h(cameraView, {});
                    },
                }).mount(marker.element);
                marker.customPicker = true; // 设置才能可点击/鼠标移入等 事件
                console.log(item);
                /* marker.on('mouseenter', () => {
                    console.log(11);
                }); */
                marker.on('singleClick', () => {
                    // 点击事件
                    console.log(22);
                });
                /* marker.on('dblclick', () => {
                    // 双击事件
                    console.log(33);
                }); */
            },
        });
    });
}

/* 加载/创建点位 */
function loadPoint() {
    return new Promise((resolve, reject) => {
        // loadTwins 会自动创建 marker、线、面
        const list = window.twinsManagerIns.twinsArray.filter((item) =>
            [
                'SHI_JIAO_BAO_CUN',
                'CE_SHI_MIAN',
                'XIAN_CE_SHI',
                'CE_SHI_SHE_XIANG_TOU',
            ].includes(item.twinClassCode)
        );
        window.twinsManagerIns.loadTwins({
            list, // 设备列表数据
            mode: 'splitNormal',
            splitNum: 10,
            customMarker: { size: 0 },
            cb: () => {
                resolve();
            },
        });
    });
}

/* 初始化点位 */
function initPoint() {
    return new Promise((resolve, reject) => {
        if (window.twinsManagerIns) return; // 只初始化一次
        window.twinsManagerIns = window.TiIns.CampusTwinsManager({
            app: window.app, // HTINGJS实例
            core: window.TiIns.Core,
            inEarth: true, // 园区是否加载在地球上 默认false
            queryParam: {
                // 查询参数-查询当前场景的所有点位
                sceneId: window.campusManagerIns.curSceneData.uuid,
            },
            initCb: () => {
                // 加载完毕回调
                console.log('加载孪生体实例初始化完毕');
                resolve();
            },
        });
    });
}

/* 移动相机视角 */
function flyTo() {
    window.app.camera.flyTo({
        isEarth: true, // 是否在地球上，默认 false。在地球上使用需要传 true
        position: [1.6477120832885233, 62.52945650018469, 219.00229195754616],
        target: [0, 26.359690061562485, 0],
        complete() {
            // 飞行结束时的回调函数
        },
    });
}
